var api = require('appconfig.js');
/*格式化时间 */
const formatCTime = (date) => {
    var time = date.replace('T', ' ');
    var index = time.indexOf('.');
    if (index > 0) {
        time = time.substr(0, index);
    }
    return time;
};
//格式化年月日时分秒
const formatTime = (date) => {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const hour = date.getHours();
    const minute = date.getMinutes();
    const second = date.getSeconds();
    return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':');
};
const formatTimecom = (date) => {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const hour = date.getHours();
    const minute = date.getMinutes();
    const second = date.getSeconds();
    return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':');
};
//格式化年月日
const formatDate = (date) => {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    return [year, month, day].map(formatNumber).join('-');
};
//当月第一天
const formatDateOne = (date) => {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = '01';
    return [year, month, day].map(formatNumber).join('-');
};
const getStartDayOfWeek = (date) => {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    console.log(day);
    const nowDayOfWeek = date.getDay();
    const day = nowDayOfWeek || 7;
    const nowday = date.getDate();
    return [year, month, nowday + 1 - day].map(formatNumber).join('-');
};
/**
 * 获得本周的结束时间
 *
 * @returns
 */
const getEndDayOfWeek = (date) => {
    const nowDayOfWeek = date.getDay();
    const day = nowDayOfWeek || 7;
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const nowday = date.getDate() + 7 - day;
    return [year, month, nowday].map(formatNumber).join('-');
};

//前一个月
const beforeMonth = (date) => {
    date.setMonth(date.getMonth() - 1);
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    return [year, month, day].map(formatNumber).join('-');
};
const formatNumber = (n) => {
    n = n.toString();
    return n[1] ? n : '0' + n;
};
function getDateMonth(today) {
    var dd;
    if (today) {
        dd = new Date(today);
    } else {
        dd = new Date();
    }
    var y = dd.getFullYear();
    var m = dd.getMonth() + 1; //获取当前月份的日期
    if (m < 10) {
        m = '0' + m;
    }
    return y + '-' + m;
}

/**
 * 用于判断空，Undefined String Array Object
 */
function isEmpty(item) {
    return item == null || item == 'undefined' || item == undefined || item == '' || item == 'null';
}
function isMobile(str) {
    var myreg = /^[1][0-9]{10}$/;
    if (!myreg.test(str)) {
        return false;
    } else {
        return true;
    }
}
function changeMiddlepic(jpg) {
    return jpg.replace('0/w/320/h/320', '0/w/640/h/640');
}
function changeBigpic(jpg) {
    return jpg.replace('0/w/320/h/320', '0/w/0').replace('0/w/640/h/640', '0/w/0');
}

/** 封封微信的的request*/
function request(data, method, other) {
    method = method ? method : 'POST';
    return new Promise(function (resolve, reject) {
        uni.request({
            url: other ? other : api.httpurl,
            data: data ? data : null,
            method: method,
            header: {
                'Content-Type': method == 'GET' ? 'application/json' : 'application/x-www-form-urlencoded'
            },
            success: function (res) {
                //接口调用成功
                if (res.data.code == 0 || res.data.return_code == 200 || res.statusCode == 200) {
                    resolve(res.data);
                } else {
                    if (res.data.code != 0 && res.data.code !== 1000) {
                        uni.showModal({
                            title: '提示',
                            content: res.data.Message
                        });
                    }
                }
            },
            fail: function (err) {
                // fail调用接口失败
                reject(err);
                uni.showModal({
                    title: '提示',
                    content: '请求异常，请查看网络是否正常！'
                });
            }
        });
    });
}
/*提示 */
function showErrorToast(msg) {
    uni.showToast({
        title: msg
    });
}
/*某个数组分割为N个对象一组 */
function group(data, n) {
    var result = [];
    for (var i = 0; i < data.length; i += n) {
        result.push(data.slice(i, i + n));
    }
    return result;
}
// 编码，配合encodeURIComponent使用
function base64_encode(str) {
    var c1;
    var c2;
    var c3;
    var base64EncodeChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
    var i = 0;
    var len = str.length;
    var strin = '';
    while (i < len) {
        c1 = str.charCodeAt(i++) & 255;
        if (i == len) {
            strin += base64EncodeChars.charAt(c1 >> 2);
            strin += base64EncodeChars.charAt((c1 & 3) << 4);
            // strin += "==";
            strin += '$$';
            break;
        }
        c2 = str.charCodeAt(i++);
        if (i == len) {
            strin += base64EncodeChars.charAt(c1 >> 2);
            strin += base64EncodeChars.charAt(((c1 & 3) << 4) | ((c2 & 240) >> 4));
            strin += base64EncodeChars.charAt((c2 & 15) << 2);
            // strin += "=";
            strin += '$';
            break;
        }
        c3 = str.charCodeAt(i++);
        strin += base64EncodeChars.charAt(c1 >> 2);
        strin += base64EncodeChars.charAt(((c1 & 3) << 4) | ((c2 & 240) >> 4));
        strin += base64EncodeChars.charAt(((c2 & 15) << 2) | ((c3 & 192) >> 6));
        strin += base64EncodeChars.charAt(c3 & 63);
    }
    return strin;
}
// 解码，配合decodeURIComponent使用
function base64_decode(input) {
    var base64EncodeChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
    var output = '';
    var chr1;
    var chr2;
    var chr3;
    var enc1;
    var enc2;
    var enc3;
    var enc4;
    var i = 0;
    input = input.replace(/[^A-Za-z0-9\+\/\=]/g, '');
    while (i < input.length) {
        enc1 = base64EncodeChars.indexOf(input.charAt(i++));
        enc2 = base64EncodeChars.indexOf(input.charAt(i++));
        enc3 = base64EncodeChars.indexOf(input.charAt(i++));
        enc4 = base64EncodeChars.indexOf(input.charAt(i++));
        chr1 = (enc1 << 2) | (enc2 >> 4);
        chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
        chr3 = ((enc3 & 3) << 6) | enc4;
        output = output + String.fromCharCode(chr1);
        if (enc3 != 64) {
            output = output + String.fromCharCode(chr2);
        }
        if (enc4 != 64) {
            output = output + String.fromCharCode(chr3);
        }
    }
    return utf8_decode(output);
}
//倒计时
function countDown(row) {
    // 获取当前时间，同时得到活动结束时间数组
    let newTime = new Date().getTime();
    // 对结束时间进行处理渲染到页面
    var time = row.Fetime.replace('T', ' ');
    var index = time.indexOf('.');
    if (index > 0) {
        time = time.substr(0, index);
    }
    let endTime = new Date(Date.parse(time.replace(/-/g, '/'))).getTime();
    let obj = null;
    // 如果活动未结束，对时间进行处理
    if (endTime - newTime > 0) {
        let time = (endTime - newTime) / 1000;
        // 获取天、时、分、秒
        let day = parseInt(time / 86400);
        let hou = parseInt((time % 86400) / 3600);
        let min = parseInt(((time % 86400) % 3600) / 60);
        let sec = parseInt(((time % 86400) % 3600) % 60);
        obj = {
            day: day < 10 ? '0' + day : day,
            hou: hou < 10 ? '0' + hou : hou,
            min: min < 10 ? '0' + min : min,
            sec: sec < 10 ? '0' + sec : sec
        };
        //console.log(day + "天" + hou + ":" + min + ":" +sec);
    } else {
        //活动已结束，全部设置为'00'
        obj = {
            day: '00',
            hou: '00',
            min: '00',
            sec: '00'
        };
        row.Ftsatus = 2;
    }
    row.obj = obj;
    return row;
}
//使用：util.buildTree(jsonlist,"id","pid"))  //传入的值 列表 ，本对象的id，父对象的pid
function buildTree(list, idstr, pidstr) {
    var result = [];
    var temp = {};
    for (i = 0; i < list.length; i++) {
        temp[list[i][idstr]] = list[i]; //将数组转成对象类型
    }

    for (j = 0; j < list.length; j++) {
        tempVp = temp[list[j][pidstr]]; //获取每一个子对象的父对象
        if (tempVp) {
            //判断父对象是否存在，如果不存在直接将对象放到第一层
            if (!tempVp['children']) {
                tempVp['children'] = [];
            } //如果父元素的nodes对象不存在，则创建数组
            tempVp['children'].push(list[j]); //将本对象压入父对象的nodes数组
        } else {
            result.push(list[j]); //将不存在父对象的对象直接放入一级目录
        }
    }

    return result;
}
//json数组去重
function uniqueArray(array, key) {
    var result = [array[0]];
    for (var i = 1; i < array.length; i++) {
        var item = array[i];
        var repeat = false;
        for (var j = 0; j < result.length; j++) {
            if (item[key] == result[j][key]) {
                repeat = true;
                break;
            }
        }
        if (!repeat) {
            result.push(item);
        }
    }
    return result;
}
//版本比较
function compareVersion(v1, v2) {
    v1 = v1.split('.');
    v2 = v2.split('.');
    const len = Math.max(v1.length, v2.length);
    while (v1.length < len) {
        v1.push('0');
    }
    while (v2.length < len) {
        v2.push('0');
    }
    for (let i = 0; i < len; i++) {
        const num1 = parseInt(v1[i]);
        const num2 = parseInt(v2[i]);
        if (num1 > num2) {
            return 1;
        } else if (num1 < num2) {
            return -1;
        }
    }
    return 0;
}
module.exports = {
    formatCTime: formatCTime,
    formatTime: formatTime,
    formatTimecom: formatTimecom,
    formatDate: formatDate,
    beforeMonth: beforeMonth,
    getDateMonth,
    request,
    showErrorToast,
    group,
    base64_encode,
    base64_decode,
    countDown,
    buildTree,
    uniqueArray,
    isMobile,
    isEmpty,
    changeMiddlepic,
    changeBigpic,
    formatDateOne,
    getStartDayOfWeek,
    getEndDayOfWeek,
    compareVersion
};
